package com.whfc.common.util;

import com.whfc.common.exception.BizException;
import com.whfc.common.result.ResultEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPOutputStream;

/**
 * @author qzexing
 * @version 1.0
 * @date 2021/11/16 18:48
 */
public class GzipUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(GzipUtils.class);

    /**
     * gzip压缩字符串
     *
     * @param data 数据
     * @return 字节
     */
    public static byte[] compress(String data) {
        LOGGER.info("gzip压缩字符串, data.length:{}", data.length());
        try {
            byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            // 压缩
            GZIPOutputStream gos = new GZIPOutputStream(os);
            gos.write(bytes, 0, bytes.length);
            gos.finish();
            byte[] output = os.toByteArray();
            os.flush();
            os.close();
            return output;
        } catch (Exception e) {
            LOGGER.warn("gzip压缩错误", e);
            throw new BizException(ResultEnum.FAILURE.getCode(), "系统错误，请稍后再试");
        }
    }


}
